<template>
  <v-container>
    <v-row>
      <v-col cols="12">
        <h1 class="text-h3 mb-4">{{ $t('message.contact') }}</h1>
      </v-col>
      <v-col cols="12" md="6">
        <v-card class="pa-4">
          <v-form ref="form" v-model="valid">
            <v-text-field
              v-model="form.name"
              label="Name / 姓名"
              outlined
              required
              :rules="nameRules"
            ></v-text-field>
            <v-text-field
              v-model="form.email"
              label="Email / 邮箱"
              outlined
              required
              type="email"
              :rules="emailRules"
            ></v-text-field>
            <v-textarea
              v-model="form.message"
              label="Message / 留言"
              outlined
              required
              :rules="messageRules"
            ></v-textarea>
            <v-btn 
              color="primary" 
              large 
              block 
              :disabled="!valid || isSubmitting"
              :loading="isSubmitting"
              @click="submitForm"
            >
              {{ isSubmitting ? 'Submitting... / 提交中...' : 'Submit / 提交' }}
            </v-btn>
          </v-form>
          
          <!-- 提交状态提示 -->
          <v-alert
            v-if="submitStatus"
            :type="submitStatus.type"
            class="mt-4"
            dismissible
            @click:close="submitStatus = null"
          >
            {{ submitStatus.message }}
          </v-alert>
        </v-card>
      </v-col>
      <v-col cols="12" md="6">
        <v-card class="pa-4 height-100">
          <v-card-title>{{ $t('contact.info.title') || 'Contact Information / 联系方式' }}</v-card-title>
          <v-card-text>
            <v-list>
              <v-list-item>
                <template v-slot:prepend>
                  <v-icon>mdi-email</v-icon>
                </template>
                <v-list-item-title>yuri@exxonte.com</v-list-item-title>
              </v-list-item>
              <v-list-item>
                <template v-slot:prepend>
                  <v-icon>mdi-phone</v-icon>
                </template>
                <v-list-item-title>-</v-list-item-title>
              </v-list-item>
              <v-list-item>
                <template v-slot:prepend>
                  <v-icon>mdi-map-marker</v-icon>
                </template>
                <v-list-item-title>{{ $t('contact.info.addressValue') }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: 'ContactPage',
  data() {
    return {
      valid: false,
      isSubmitting: false,
      submitStatus: null,
      form: {
        name: '',
        email: '',
        message: ''
      },
      nameRules: [
        v => !!v || '姓名不能为空 / Name is required'
      ],
      emailRules: [
        v => !!v || '邮箱不能为空 / Email is required',
        v => /.+@.+\..+/.test(v) || '请输入有效的邮箱地址 / Please enter a valid email address'
      ],
      messageRules: [
        v => !!v || '留言不能为空 / Message is required'
      ]
    }
  },
  methods: {
    async submitForm() {
      // 验证表单
      const { valid } = await this.$refs.form.validate();
      if (!valid) return;

      this.isSubmitting = true;
      this.submitStatus = '';

      try {
        // 发送到PHP处理脚本
        const response = await fetch('/contact-handler.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: this.form.name,
            email: this.form.email,
            message: this.form.message
          })
        });

        const result = await response.json();
        
        if (result.success) {
          this.submitStatus = {
            type: 'success',
            message: result.message || '感谢您的留言！我们已收到您的信息，会尽快回复您。'
          };
          // 清空表单
          this.form = {
            name: '',
            email: '',
            message: ''
          };
          this.$refs.form.resetValidation();
        } else {
          this.submitStatus = {
            type: 'error',
            message: result.message || '提交失败，请稍后重试'
          };
          console.error('提交失败:', result.message);
        }
      } catch (error) {
        this.submitStatus = {
          type: 'error',
          message: '网络错误，请检查网络连接后重试'
        };
        console.error('提交错误:', error);
      } finally {
        this.isSubmitting = false;
      }
    },
    
    // 下载联系信息为文件
    downloadContactInfo(content) {
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `contact_${new Date().toISOString().split('T')[0]}.txt`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    },
    
    // 保存到本地存储
    saveToLocalStorage(contactRecord) {
      const existingContacts = JSON.parse(localStorage.getItem('contactSubmissions') || '[]')
      existingContacts.push(contactRecord)
      localStorage.setItem('contactSubmissions', JSON.stringify(existingContacts))
    }
  }
}
</script>

<style scoped>
.height-100 {
  height: 100%;
}
</style>